package com.example.socketdemo.nio.two;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class Client {
    // 客户端通道
    private SocketChannel sChannel;
    // 选择器
    private Selector selector;
    // 监听端口
    private static final int PORT = 9999;

    public Client(){
        try {
            selector = Selector.open();

            sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", PORT));

            sChannel.configureBlocking(false);

            sChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Client client = new Client();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    client.readMessage();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Scanner sc = new Scanner(System.in);

        while (sc.hasNext()){
            System.out.println("请说：");
            String str = sc.next();

            client.sendInfo(str);

        }

    }

    private void sendInfo(String str) {

        try {
            ByteBuffer buf = ByteBuffer.allocate(1024);
            buf.put(str.getBytes());
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void readMessage() throws IOException {

        while(selector.select() > 0){
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();

            while(it.hasNext()){
                SelectionKey sk = it.next();

                if(sk.isReadable()){
                    SocketChannel channel = (SocketChannel) sk.channel();

                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    channel.read(buf);
                    System.out.println(new String(buf.array(), 0, buf.remaining()).trim());

                }

                it.remove();
            }
        }
    }
}
